package ua.senfiron.vk.photo.viewer;

import ua.senfiron.vk.photo.viewer.ConnectivityChangeReceiver.ConnectivityChangeListener;
import ua.senfiron.vk.photo.viewer.util.NetworkUtilities;
import ua.senfiron.vk.photo.viewer.vkprovider.VkProvider;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebViewDatabase;
import android.widget.ProgressBar;

import com.androidquery.util.AQUtility;

public class VkLoginActivity extends ActionBarActivity {

    private ProgressBar mProgressBar;
    private WebView mWebView;
    private VkProvider mVkProvider;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vklogin);
        
        mProgressBar = (ProgressBar) findViewById(R.id.progressVkLogin);
        mWebView = (WebView) findViewById(R.id.webViewVkLogin);
        mVkProvider = VkProvider.getInstance();
        
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.setFocusable(true);
        mWebView.setFocusableInTouchMode(true);
        mWebView.requestFocus(View.FOCUS_DOWN);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setSupportZoom(false);
        webSettings.setUseWideViewPort(true);
        
        mWebView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_UP:
                    if (!v.hasFocus()) {
                        v.requestFocus();
                    }
                    break;
            }
            return false;
            }
        });
        mWebView.setWebViewClient(new VkLoginWebViewClient());
    }
    
    @SuppressWarnings("deprecation")
    @Override
    protected void onStart() {
        super.onStart();

        //Load preferences
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        boolean saveFormData = pref.getBoolean("save_form_data", false);
        boolean stayLoggedIn = pref.getBoolean("stay_logged_in", false);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setSaveFormData(saveFormData);
        webSettings.setSavePassword(saveFormData);
        
        if(!saveFormData) {
            WebViewDatabase webViewDb = WebViewDatabase.getInstance(this);
            webViewDb.clearFormData();
            webViewDb.clearHttpAuthUsernamePassword();
            webViewDb.clearUsernamePassword();
        }

        boolean userLoggedIn = (mVkProvider.getAccessToken() != null);
        if(!stayLoggedIn) {
            mVkProvider.clearSharedPreferences(this);
            if(userLoggedIn) {
                mVkProvider.logOut(this);
            }
        } else {
            if(userLoggedIn) {
                exit();
                return;
            } else if (mVkProvider.loadFromSharedPreferences(this)) {
                startAlbumListActivity();
                return;
            }
        }
        if(mWebView.getUrl() != mVkProvider.getLoginURL())
            loadLoginUrl();
    }
    
    private void loadLoginUrl() {
        if(ConnectivityChangeReceiver.isNetworkConnected(this)) {
            mWebView.loadUrl(mVkProvider.getLoginURL());
        } else {
            NetworkUtilities.showInternetNotAvaliableDialog(this);
            ConnectivityChangeReceiver.setListener(new ConnectivityChangeListener() {
                
                @Override
                public void onNetworkConnected() {
                    mWebView.loadUrl(mVkProvider.getLoginURL());
                }
            });
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(isTaskRoot()){
            long triggerSize = 3000000; //starts cleaning when cache size is larger than 3M
            long targetSize = 2000000;  //remove the least recently used files until cache size is less than 2M
            AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.vk_login, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_refresh:
            loadLoginUrl();
            return true;
         case R.id.action_exit:
            exit();
            return true;
        case R.id.action_settings:
            Intent intent = new Intent(VkLoginActivity.this, SettingsActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
        
    private void exit() {      
        mVkProvider.clearData();
        Intent resultIntent = new Intent();
        setResult(Activity.RESULT_OK, resultIntent);
        this.finish();
    }
    
    private void startAlbumListActivity()
    {
        Intent intent = new Intent(VkLoginActivity.this, AlbumListActivity.class);
        startActivity(intent);
    }
    
    private class VkLoginWebViewClient extends WebViewClient {
        
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mHideProgressHandler.removeCallbacks(mHideProgressRunnable);
            mHideProgressHandler.postDelayed(mHideProgressRunnable, 100);
        }
        
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
           super.onPageStarted(view, url, favicon);
            mHideProgressHandler.removeCallbacks(mHideProgressRunnable);
            view.setVisibility(View.GONE);
            mProgressBar.setVisibility(View.VISIBLE);
        }
        
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(mVkProvider.extractTokenFromUrl(url))
            {
                mHideProgressHandler.removeCallbacks(mHideProgressRunnable);
                mVkProvider.saveToSharedPreferences(VkLoginActivity.this);
                startAlbumListActivity();
                return true;
            }

            view.loadUrl(url);
            return true;
        }
        
        Handler mHideProgressHandler = new Handler();
        Runnable mHideProgressRunnable = new Runnable() {
            @Override
            public void run() {
                mProgressBar.setVisibility(View.GONE);
                mWebView.setVisibility(View.VISIBLE);
            }
        };
    }
}
